package com.chaopei.day10.review;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Author Corday 天涯
 * @Date 2022/3/16 9:40
 */
public class MyServer {
    public static void main(String[] args) {
//        要首先启动此处的服务端程序,再启动另一个客户端程序
      go();
    }//main

    public static void go() {
//网络字符输出流PrintWrite
        InputStream in = null;
        OutputStream out = null;
        BufferedReader br = null;
        PrintWriter pw = null;
        Socket socket = null;
        ServerSocket serverSocket = null;
//        创建各种对象
        try {
            System.out.println("服务端已启动,等待连接...");
            serverSocket = new ServerSocket(9080);
            //服务端跟客户连接并生成socket对象
            socket = serverSocket.accept();
            in = socket.getInputStream();
            out = socket.getOutputStream();
            br = new BufferedReader(new InputStreamReader(in));
            String msg = br.readLine();
            if(msg!=null){
                System.out.println("接收客户端:"+msg);
            }else{
                System.out.println("客户端无反应!");
            }
            //创建网络字符输出流对象
            pw = new PrintWriter(out,true);
            pw.println("这里是服务端,你是谁!");
//            关闭各种流
            out.close();
            in.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
